from PIL import Image, ImageDraw, ImageFont
import qrcode
import pygame
import glob
import fitz
import os

#生成PDF的背景图和文本框的格式配置
backMode = {
    # 背景图属性，我的背景图上需要添加一个二维码和多个文本框
    "back_url": "./static/CSS/a.png",
    "size": (3024, 3876),
    "QR": {
        # 二维码属性
        "frame": (500, 500),  # 大小
        "position": (2440, 80),  # 位置
    },
    "text": [{
        # 文本框属性
        "size": 70,  # 字号
        "ttf": "FZXBSJW.TTF",  # 字体
        "color": "",  # 颜色
        "position": (80, 120),
        "frame": (2400, 20),
    }, {
        "size": 70,
        "ttf": "FZXBSJW.TTF",
        "color": "",
        "position": (40, 240),
        "frame": (2400, 20),
    }, {
        "size": 70,
        "ttf": "FZXBSJW.TTF",
        "color": "",
        "position": (40, 360),
        "frame": (2400, 20),
    }, {
        "size": 70,
        "ttf": "FZXBSJW.TTF",
        "color": "",
        "position": (40, 480),
        "frame": (2400, 20),
    }, {
        "size": 70,
        "ttf": "FZXBSJW.TTF",
        "color": "",
        "position": (40, 600),
        "frame": (2400, 20),
    }, ],
}
#生成二维码
def make_QR(content, sizeW=0, sizeH=0):  # 创建二维码
    qr = qrcode.QRCode(version=3, box_size=3, border=1, error_correction=qrcode.constants.ERROR_CORRECT_H)
    qr.add_data(content)
    qr.make(fit=True)
    img = qr.make_image()
    if sizeW == 0 and sizeH == 0:
        return img
    w, h = img.size
    if sizeW < w or sizeH < h:
        return None
    img = img.resize((sizeW, sizeH), Image.ANTIALIAS)
    return img
#合并图片 combine picture
def com_pic(topimg, backimg, position):  # 合并图片
    nodeA = position
    w, h = topimg.size
    nodeB = (position[0] + w, position[1] + h)
    backimg.paste(topimg, (nodeA[0], nodeA[1], nodeB[0], nodeB[1]))
    return backimg
#给单个文本框填充数据
def write_line(backimg, text, tmode):  # 给单个文本框填充数据
    # myfont = ImageFont.truetype(tmode["ttf"], size=tmode["size"])
    myfont=ImageFont.truetype(os.path.join("fonts", "simsun.ttc"), size=tmode["size"])
    draw = ImageDraw.Draw(backimg)
    tend = len(text)
    while True:
        text_size = draw.textsize(text[:tend], font=myfont)  # 文本图层的尺寸
        # print(text_size)
        if text_size[0] <= tmode["frame"][0]:
            break
        else:
            tend -= 1  # 文本太长，调整文本长度
    draw.text((tmode["position"][0], tmode["position"][1]), text[:tend], font=myfont)

    return backimg, tend
#写文本
def write_text(img, text, tmodeList):  # 写文本
    tlist = text.split("\n")
    mnum = 0
    draw = ImageDraw.Draw(img)
    for t in tlist:
        tbegin = 0
        tend = len(t)
        while True:
            img, tend = write_line(img, t[tbegin:tend], tmodeList[mnum])
            mnum += 1
            if tbegin + tend == len(t) or mnum == len(tmodeList):
                break
            else:
                tbegin = tbegin + tend
                tend = len(t)
        if mnum == len(tmodeList):
            break
    return img
#绘制包含二维码和文本的图片
def make_pic(mode, text, url):
    img = Image.open(mode["back_url"])#读取背景图片
    img = Image.open(r'./static/CSS/a.png')  # 读取背景图片
    QR_res = make_QR(url, mode["QR"]["frame"][0], mode["QR"]["frame"][1])  # 创建二维码
    img = com_pic(QR_res, img, mode["QR"]["position"])  # 合成1
    img = write_text(img, text, mode["text"])  # 写文本
    img.show()
    img.save(r'./static/download/output.png', quality=100)
#将文本文件TXT转为字符串
def txt2String(txt_path):
    String = ""
    with open(txt_path, 'r')as f:
        content = f.read().splitlines()
        my_data =content
    f.close()
    for i in range(len(my_data)):
        temp = my_data[i]
        temp += ' \n '
        my_data[i] = temp
        String += my_data[i]

    return String
#生成PDF
def make_pdf():#首先将文本转化为图片，之后将所有图片合并

    img_path = r"./static/download"
    pdf_path = r"./static/download"
    pdf_name = r"1.pdf"

    a = txt2String('./static/download/data.txt')
    make_pic(backMode, a, "https://imed.nimte.ac.cn/")
    doc = fitz.open()
    imgdoc = fitz.open('./static/download/output.png')
    pdfbytes = imgdoc.convertToPDF()
    imgpdf = fitz.open('pdf',pdfbytes)
    doc.insertPDF(imgpdf)
    doc.save('./static/download/output.PDF')
    doc.close()

    doc = fitz.open()

    for img in sorted(glob.glob(img_path + "/*.png")):
        imgdoc = fitz.open(img)
        pdfbytes = imgdoc.convertToPDF()
        imgpdf = fitz.open("pdf",pdfbytes)
        doc.insertPDF(imgpdf)
    doc.save('./static/download/output1.PDF')
    doc.close